package cn.yh.springbootjwt.service.impl;

import cn.yh.springbootjwt.domain.entity.OrdersDo;
import cn.yh.springbootjwt.domain.query.ShoppingCartIds;
import cn.yh.springbootjwt.domain.vo.OrdersDtlListVo;
import cn.yh.springbootjwt.domain.vo.OrdersDtlVo;
import cn.yh.springbootjwt.mapper.OrdersDtlMapper;
import cn.yh.springbootjwt.mapper.OrdersMapper;
import cn.yh.springbootjwt.service.IOrdersService;
import cn.yh.springbootjwt.utils.JWTUtils;
import cn.yh.springbootjwt.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;



@Service
public class OrdersServiceImpl implements IOrdersService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrdersDtlMapper ordersDtlMapper;

    @Override
//    @Transactional
    public int createOrders(ShoppingCartIds shoppingCartIds) {
        Long userId = JWTUtils.getUserIdByClaim();

        // 1. 创建订单
        OrdersDo ordersDo = new OrdersDo();
        ordersDo.setUserId(userId);
        ordersDo.setOrderNum(UUID.randomUUID().toString().replace("-", ""));
        ordersDo.setOrderTime(TimeUtils.getChinaTimeAsDate());
        ordersDo.setCreateBy(JWTUtils.getUsernameByClaim());
        ordersDo.setUpdateBy(JWTUtils.getUsernameByClaim());
        ordersDo.setCreateTime(TimeUtils.getChinaTimeAsDate());
        ordersDo.setUpdateTime(TimeUtils.getChinaTimeAsDate());
        if (ordersMapper.insertOrders(ordersDo) <= 0) {
            return 0;
        }
        // 2. 获取新订单ID（确保MyBatis配置 useGeneratedKeys 以及）
        System.out.println("订单创建成功，orderId：" + ordersDo.getOrderId());
        int successCount = 0;
        for (Long cartId : shoppingCartIds.getShoppingCartIds()) {
            try {
                OrdersDtlVo dtlVo = ordersDtlMapper.selectOrderDtl(userId, cartId);
                if (dtlVo == null) {
                    System.out.println("购物车项不存在: "+cartId);;
                    continue; // 跳过无效
                }
                dtlVo.setOrderId(ordersDo.getOrderId());
                ordersDtlMapper.insertOrdersDtl(dtlVo);
                successCount++;
            } catch (Exception e) {
                System.out.println("处理购物车项失败: "+cartId);
                throw new RuntimeException("订单创建失败", e); // 回滚
            }
        }
        if (successCount == 0 ){
            ordersMapper.deleteByOrderDtlId(ordersDo.getOrderId());
            throw new RuntimeException("未找到正确的购物车项，订单创建失败"); // 回滚
//                return 0; // 全部失败
        }
        return successCount;
    }

    @Override
    public List<OrdersDtlListVo> selectOrdersDtlList() {
        return ordersMapper.selectOrdersDtlList(JWTUtils.getUserIdByClaim());
    }

}
// 3. 处理每个购物车项
//        int successCount = 0;
//        for ( shoppingCartId : shoppingCartIds) {
//            try {
//                OrdersDtlVo ordersDtlVo = ordersDtlMapper.selectOrderDtl(userId, shoppingCartId);
//                if (ordersDtlVo == null) {
//                    continue;
//                }
//
//                // 设置订单ID
//                ordersDtlVo.setOrderId(orderId);
//
//                if (ordersDtlMapper.insertOrdersDtl(ordersDtlVo) > 0) {
//                    successCount++;
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                // 记录错误但继续处理其他项
//            }
//        }

//        return successCount > 0 ? 1 : 0;